package com.moxiao.yfjh.module.blind.common;


import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;
import com.moxiao.yfjh.framework.common.util.jpush.JgPushSendVo;
import com.moxiao.yfjh.framework.common.util.jpush.JpushUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;

@Component
@Slf4j
public class JgPushSend {

    private final static String APPKER = "18e80c43bb2b7a4e36bd976a";

    private final static String MASTERSECRET = "8dabd90af67a1be73b083f27";

    private JPushClient jPushClient;

    /*public static void main(String[] args) {
        JPushClient jp = new JPushClient("8dabd90af67a1be73b083f27", "18e80c43bb2b7a4e36bd976a");
        try {
            // 给所有用户发
//            PushPayload pushPayload = JpushUtil.buildPushObject_android_all_alertWithTitle("中奖通知", "缘分计划",
//                    "恭喜你中了100个亿", "myAlias/pages/my/MyProfile/MyProfile");
            List<String> alias = new ArrayList<>();
            alias.add("10067");
            JgPushSendVo jgPushSendVo = new JgPushSendVo();
            jgPushSendVo.setAlias(alias);
            jgPushSendVo.setUrl("myAlias/pages/my/MyProfile/MyProfile");
            jgPushSendVo.setMsgTitle("缘分计划");
            jgPushSendVo.setContent("他要和你生猴子");
            jgPushSendVo.setNotificationTitle("你被美女选中啦");
            PushPayload pushPayload = JpushUtil.buildPushObject_all_alias_alertWithTitle(jgPushSendVo);

            PushResult pushResult = jp.sendPush(pushPayload);
            if (pushResult.getResponseCode() == 200) {
                System.out.println(pushResult);
            }
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.getStatus();
            e.getErrorCode();
            e.getErrorMessage();
        }
    }*/

    /**
     * 初始化客户端
     */
    @PostConstruct
    public void init() throws Exception {
        log.info("极光推送客户端初始化");
        jPushClient = new JPushClient(MASTERSECRET, APPKER);
    }

    /**
     * 推送给设备标识参数的用户
     */
    public int sendToRegistrationId(JgPushSendVo jgPushSendVo) {
        int result = 0;
        try {

            PushPayload pushPayload = JpushUtil.buildPushObject_all_alias_alertWithTitle(jgPushSendVo);
            PushResult pushResult = jPushClient.sendPush(pushPayload);
            if (pushResult.getResponseCode() == 200) {
                result = 1;
            }
            log.info("[极光推送]PushResult result is {}", pushResult);
        } catch (APIConnectionException e) {
            log.error("[极光推送]Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.info("[极光推送]Error Message: {}", e.getErrorMessage());
        }

        return result;
    }

    /**
     * 推送给设备标识参数的用户（定时）

    public int sendToRegistrationId2(JgPushSendVo jgPushSendVo, String time) {
        JPushClient jPushClient = new JPushClient(MASTERSECRET, APPKER);
        int result = 0;
        try {
            PushPayload pushPayload = JpushUtil.buildPushObject_all_alias_alertWithTitle(jgPushSendVo);
            ScheduleResult scheduleResult = jPushClient.createSingleSchedule("测试", time, pushPayload);
            if (scheduleResult.getResponseCode() == 200) {
                result = 1;
            }
            log.info("[极光推送]ScheduleResult result is " + scheduleResult);
        } catch (APIConnectionException e) {
            log.error("[极光推送]Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("[极光推送]Error response from JPush server. Should review and fix it. ", e);
            log.info("[极光推送]HTTP Status: " + e.getStatus());
            log.info("[极光推送]Error Code: " + e.getErrorCode());
            log.info("[极光推送]Error Message: " + e.getErrorMessage());
        }

        return result;
    }
     */
    /**
     * 发送给安卓用户
     */
    public void sendToAllAndroid(JgPushSendVo jgPushSendVo) {

        CompletableFuture.runAsync(() -> {
            try {
                PushPayload pushPayload = JpushUtil.buildPushObject_android_all_alertWithTitle(jgPushSendVo);
                PushResult pushResult = jPushClient.sendPush(pushPayload);
                if (pushResult.getResponseCode() == 200) {
                    log.info("[极光推送] 消息推送成功,code：{} ", pushResult);
                }
            } catch (APIConnectionException e) {
                log.error("[极光推送]连接错误，请稍后重试. ", e);
            } catch (APIRequestException e) {
                log.info("[极光推送]HTTP Status:{} ", e.getStatus());
                log.info("[极光推送]Error Code: {}", e.getErrorCode());
            }
        });
    }

    /**
     * 发送给所有用户
     */
    public void sendToAll(JgPushSendVo jgPushSendVo) {
        CompletableFuture.runAsync(() -> {
            try {
                PushPayload pushPayload = JpushUtil.buildPushObject_android_and_ios(jgPushSendVo);
                PushResult pushResult = jPushClient.sendPush(pushPayload);
                if (pushResult.getResponseCode() == 200) {
                    log.info("[极光推送] 消息推送成功,code：{} ", pushResult);
                }

            } catch (APIConnectionException e) {
                log.error("[极光推送]连接错误，请稍后重试. ", e);
            } catch (APIRequestException e) {
                log.info("[极光推送]HTTP Status:{} ", e.getStatus());
                log.info("[极光推送]Error Code: {}", e.getErrorCode());
            }
        });
    }

    /**
     * 发送给所有用户(定时推送)

     public int sendToAll2(JgPushSendVo jgPushSendVo, String time) {
        int result = 0;
        try {
            PushPayload pushPayload = JpushUtil.buildPushObject_android_and_ios(jgPushSendVo);
            ScheduleResult scheduleResult = jPushClient.createSingleSchedule("测试", time, pushPayload);
            if (scheduleResult.getResponseCode() == 200) {
                result = 1;
            }
            log.info("[极光推送]scheduleResult result is " + scheduleResult);
        } catch (APIConnectionException e) {
            log.error("[极光推送]Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("[极光推送]Error response from JPush server. Should review and fix it. ", e);
            log.info("[极光推送]HTTP Status: " + e.getStatus());
            log.info("[极光推送]Error Code: " + e.getErrorCode());
            log.info("[极光推送]Error Message: " + e.getErrorMessage());
        }
        return result;
     }  */

    public String getStr(String str) {
        String charsetName = "UTF-8"; // 指定编码格式
        String e_str = "";
        try {
            // 对URL编码字符串进行解码
            e_str = URLDecoder.decode(str, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            System.err.println("Unsupported encoding: " + charsetName);
        }
        return e_str;
    }
}
